package com.tianji.aigc.service.impl;

import com.alibaba.cloud.ai.dashscope.audio.DashScopeAudioTranscriptionModel;
import com.alibaba.cloud.ai.dashscope.audio.DashScopeAudioTranscriptionOptions;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.tianji.aigc.service.AudioService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.ai.audio.transcription.AudioTranscriptionResponse;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import reactor.core.publisher.Flux;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;

@Slf4j
@Service
@RequiredArgsConstructor
public class DashscopeAudioServiceImpl implements AudioService {

    private final SpeechSynthesisModel speechSynthesisModel;

    private final DashScopeAudioTranscriptionModel transcriptionModel;

    @Override
    public ResponseBodyEmitter ttsStream(String text) {

        var emitter = new ResponseBodyEmitter();
        log.info("开始语音合成, 文本内容：{}", text);
        var responseStream = speechSynthesisModel.stream(new SpeechSynthesisPrompt(text));
        // 订阅响应流并发送数据
        responseStream.subscribe(
                speechSynthesisResponse -> {
                    try {
                        // 安全读取 ByteBuffer 内容
                        ByteBuffer buffer = speechSynthesisResponse.getResult().getOutput().getAudio();
                        byte[] audioBytes = new byte[buffer.remaining()];
                        buffer.get(audioBytes);

                        emitter.send(audioBytes);
                    } catch (IOException e) {
                        emitter.completeWithError(e);
                    }
                },
                emitter::completeWithError,
                emitter::complete
        );
        return emitter;
    }

    @Override
    public String stt(MultipartFile audioFile) {
        log.info("开始语音转写，文件大小：{} bytes, contentType={}", audioFile.getSize(), audioFile.getContentType());

        // 1. 确定后缀（优先看文件名，没有就 fallback 到 contentType）
        String suffix = ".tmp";
        String originalFilename = audioFile.getOriginalFilename();
        if (originalFilename != null && originalFilename.contains(".")) {
            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        } else {
            String contentType = audioFile.getContentType();
            if ("audio/wav".equalsIgnoreCase(contentType)) {
                suffix = ".wav";
            } else if ("audio/mpeg".equalsIgnoreCase(contentType) || "audio/mp3".equalsIgnoreCase(contentType)) {
                suffix = ".mp3";
            }
        }

        // 2. 保存为临时文件（避免 Tomcat 临时文件在请求结束后被清理）
        File tempFile = null;
        try {
            tempFile = File.createTempFile("upload-", suffix);
            audioFile.transferTo(tempFile);
            tempFile.deleteOnExit();

            FileSystemResource resource = new FileSystemResource(tempFile);

            AudioTranscriptionResponse response = transcriptionModel.call(
                    new AudioTranscriptionPrompt(
                            resource,
                            DashScopeAudioTranscriptionOptions.builder()
                                    .withModel("sensevoice-v1")
                                    .build()
                    )
            );
            return response.getResult().getOutput();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

//        try {
//            CountDownLatch latch = new CountDownLatch(1);
//            StringBuilder stringBuilder = new StringBuilder();
//
//            tempFile = File.createTempFile("upload-", suffix);
//            audioFile.transferTo(tempFile);
//            tempFile.deleteOnExit();
//
//            Flux<AudioTranscriptionResponse> response = transcriptionModel
//                    .stream(
//                            new AudioTranscriptionPrompt(
//                                    new FileSystemResource(tempFile.toPath()),
//                                    DashScopeAudioTranscriptionOptions.builder()
//                                            .withModel("paraformer-realtime-v2")
//                                            .withSampleRate(16000)
//                                            .withFormat(DashScopeAudioTranscriptionOptions.AudioFormat.MP3)
//                                            .withDisfluencyRemovalEnabled(false)
//                                            .build()
//                            )
//                    );
//
//            response.doFinally(
//                    signal -> latch.countDown()
//            ).subscribe(
//                    resp -> stringBuilder.append(resp.getResult().getOutput())
//            );
//            latch.await();
//            return stringBuilder.toString();
//        }
//        catch (Exception e) {
//            throw new RuntimeException(e);
//        }
    }
}
